package com.junxonline.instant.terminal.netty;

import com.junxonline.instant.terminal.config.NettyConfig;
import com.junxonline.instant.terminal.netty.handler.HandshakeEventHandler;
import com.junxonline.instant.terminal.netty.handler.HeartBeatHandler;
import com.junxonline.instant.terminal.netty.handler.WebSocketFrameHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolConfig;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Netty连接通道初始化
 *
 * @author JunX
 * @date 2021-09-03
 */
@Component
public class NettyChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private NettyConfig nettyConfig;

    @Autowired
    private HeartBeatHandler heartBeatHandler;

    @Autowired
    private HandshakeEventHandler handshakeEventHandler;

    @Autowired
    private WebSocketFrameHandler webSocketFrameHandler;

    /**
     * 连接通道初始化
     *
     * @param socketChannel socket连接通道
     */
    @Override
    protected void initChannel(SocketChannel socketChannel) {
        socketChannel.pipeline()
                // 日志
                .addLast(new LoggingHandler(LogLevel.DEBUG))
                // 检测链路是否读取空闲 配合心跳Handler检测Channel是否正常
                .addLast(new IdleStateHandler(nettyConfig.getHeartBeatTime(), 0, 0, TimeUnit.SECONDS))
                // 心跳Handler
                .addLast(heartBeatHandler)
                // 编解码器
                .addLast(new HttpServerCodec())
                // 支持异步发送比较大的码流
                .addLast(new ChunkedWriteHandler())
                // 多个消息对象转换成单个消息对象
                .addLast(new HttpObjectAggregator(Integer.MAX_VALUE))
                // Websocket协议Handler
                .addLast(new WebSocketServerProtocolHandler(WebSocketServerProtocolConfig.newBuilder()
                        .websocketPath(nettyConfig.getPath())
                        .maxFramePayloadLength(Integer.MAX_VALUE)
                        .checkStartsWith(true)
                        .build()))
                // 握手事件处理器
                .addLast(handshakeEventHandler)
                // WebSocket处理器
                .addLast(webSocketFrameHandler);
    }

}
